class Removal extends egret.Sprite {
    private count: number = 20
    private balls: Array<Ball>

    public constructor() {
        super()
        this.once( egret.Event.ADDED_TO_STAGE, this.onAddToStage, this)
    }

    private onAddToStage():void {
        this.stage.scaleMode = egret.StageScaleMode.NO_SCALE
        this.balls = new Array<Ball>()
        for (let i: number = 0; i < this.count; i++) {
            let ball:Ball = new Ball(10)
            ball.x = Math.random() * this.stage.stageWidth
            ball.y = Math.random() * this.stage.stageHeight
            ball.vx = Math.random() * 2
            ball.vy = Math.random() * 2
            this.addChild(ball)
            this.balls.push(ball)
        }
        console.log(this.balls.length)
        this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
    }

    private onEnterFrame(event:egret.Event):void {
        for (let i:number = this.balls.length - 1; i >= 0; i--) {
            console.log(i)
            let ball:Ball = this.balls[i]
            ball.x += ball.vx
            ball.y += ball.vy
            if (ball.x - ball.radius > this.stage.stageWidth ||
                ball.x + ball.radius < 0 ||
                ball.y - ball.radius > this.stage.stageHeight ||
                ball.y + ball.radius < 0) {
                this.removeChild(ball)
                this.balls.splice(i, 1)
                if (this.balls.length <= 0) {
                    this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this)
                }
            }
        }
    }
}